<?php
/**
 * Created by PhpStorm.
 * User: serafina
 * Date: 2015/9/23
 * Time: 09:50
 */

function mobile_service_invoice_list($parameters){
    global $user;
    $query = db_select('invoice', 'I');
    $query->leftjoin('employee', 'E', 'E.employee_id=I.salesman_id');
    $query->leftjoin('distributor', 'D', 'D.distributor_id=I.distributor_id');
    $query->leftjoin('sales_type', 'ST', 'ST.sales_type_id=I.sales_type_id');
    $query->leftjoin('product_sku', 'SV', 'SV.product_sku_id=I.sacfvariety_id');

    $query->fields('I');

    $query->addField('D', 'distributor_name');
    $query->addField('E', 'employee_name', 'salesman');
    $query->addField('ST', 'sales_type_name');
    $query->addField('SV', 'variety_name');
    $query->addField('SV', 'proportion');
    $query->addField('SV', 'SM');
    $query->join('addr', 'da', 'da.addr_id=D.addr_id');
    $query->leftJoin('addr', 'A', 'A.addr_id=I.delivery_addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
//    if(!user_access('view all invoice') && user_access('view own invoice')){
//        $query->condition('I.author_uid',$user->uid, '=');
//    }
    $form_state = [];
    $form_state['values']['employee_list'] == 'default';
    salesman_distributor_role_relate_query_info($form_state,$query,'view all invoice','view own invoice','I');
    if (!empty($parameters['county'])) {//县级
        $query->condition('da.county_id', $parameters['county'], '=');
    } elseif (!empty($parameters['city'])) {//市级
        $query->condition('da.city_id', $parameters['city'], '=');
    } elseif (!empty($parameters['province'])) {//省级
        $query->condition('da.province_id', $parameters['province'], '=');
    }

    if (!empty($parameters['sacfvariety'])) {
        if ($parameters['sacfvariety']) {
            $query->condition('I.sacfvariety_id', $parameters['sacfvariety'], '=');
        }

    }
    if (!empty($parameters['sales_type'])) {
        if ($parameters['sales_type']) {
            $query->condition('I.sales_type_id', $parameters['sales_type'], '=');
        }
    }
    if (!empty($parameters['distributor'])) {//查询条件
        if ($parameters['distributor']) {
            $query->condition('D.distributor_id', $parameters['distributor'], '=');
        }
    }
    $datestr = '';
    if (!empty($parameters['year'])) {//查询条件
        if ($parameters['year']) {
            $datestr .= $parameters['year'] . '-';
        }
    }
    if (!empty($parameters['month'])) {//查询条件
        if ($month = $parameters['month']) {
            if ($month < 10)
                $datestr .= '0' . $parameters['month'];
            else
                $datestr .= $parameters['month'];
        }
    }
    if ($datestr) {
        $query->condition('I.invoice_date', db_like($datestr) . '%', 'LIKE');
    }
    if (!empty($parameters['employee_list'])) {//查询条件
        if ($parameters['employee_list']) {
            $query->condition('I.salesman_id', $parameters['employee_list']);
        }
    }
    //$query->leftJoin('address', 'town', 'addr.town_id=town.id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');

    $query->orderBy('I.invoice_id', 'DESC');
    if (!empty($parameters['cursor']) && !empty($parameters['comparator'])) { //游标翻页
        $query->condition('I.invoice_id', $parameters['cursor'], $parameters['comparator']);
    }
    $query->range(0,10);
    
    $results = $query->execute();
    $invoice_list = [];
    if(!empty($results)){
        foreach ($results as $result) {
            $invoice_list[] = $result;
        }
    }
    $object_invoice_list = (object)["data"=>$invoice_list];
    return  $object_invoice_list;
}

function mobile_service_invoice_add($parameters){
    global $user;
    $module_name="invoice";
    $id = !empty($parameters['id'])?$parameters['id']:'';
    if (empty($id)) { //add new brand_sales
        if(!user_access('add '.$module_name)){
            return ['option'=>0,'errorNum'=>3];
        }
        $nid = db_insert('invoice') // Table name no longer needs {}
        ->fields(array(
            'invoice_id' => $parameters['invoice_id'],
            'invoice_date' => $parameters['invoice_date'],
            'salesman_id' => $parameters['salesman_id'],
            'distributor_id' => $parameters['distributor_id'],
            'sales_type_id' => $parameters['sales_type_id'],
            'sacfvariety_id' => $parameters['sacfvariety_id'],
            'quantity' => $parameters['quantity'],
            'delivery_addr_id' => $parameters['delivery_addr_id'],
            'station_name' => $parameters['station_name'],
            'railway_bureau' => $parameters['railway_bureau'],
            'inorout' => $parameters['inorout'],
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->execute();
            $result_option = (object)["option" => 1];
            return $result_option;
    } else {
        if(!mobile_user_edit_access($module_name,'id',$id,'edit own '.$module_name,'edit all '.$module_name)){
            return ['option'=>0,'errorNum'=>3];
        }
        $nid = db_update('invoice')
        ->fields(array(
            'invoice_id' => $parameters['invoice_id'],
            'invoice_date' => $parameters['invoice_date'],
            'salesman_id' => $parameters['salesman_id'],
            'distributor_id' => $parameters['distributor_id'],
            'sales_type_id' => $parameters['sales_type_id'],
            'sacfvariety_id' => $parameters['sacfvariety_id'],
            'quantity' => $parameters['quantity'],
            'delivery_addr_id' => $parameters['delivery_addr_id'],
            'station_name' => $parameters['station_name'],
            'railway_bureau' => $parameters['railway_bureau'],
            'inorout' => $parameters['inorout'],
            'timestamp' => time(),))
            -> condition('id',$id, '=')
            ->execute();
        if($nid > 0){
            $result_option = (object)["option" => 1];
            return $result_option;
        }
        $result_option = (object)["option" => 0];
        return $result_option;
    }
}


function mobile_service_monthly_report_list($parameters){
    global $user;
    $query = db_select('distributor', 'D');
    $query->join('monthly_report', 'M', 'M.distributor_id=D.distributor_id');

    $query->fields('M');
    $query->addField('D', 'distributor_name');
    $query->join('employee','EM','M.author_uid= EM.employee_id');
    $query->addField('EM', 'employee_name');
//    if(!user_access('view all monthly_report') && user_access('view own monthly_report')){
//        $query->condition('M.author_uid',$user->uid, '=');
//    }
    $form_state = [];
    $form_state['values']['employee_list'] == 'default';
    salesman_distributor_role_relate_query_info($form_state,$query,'view all monthly_report','view own monthly_report','M');

    if (!empty($parameters['distributor'])) {//查询条件
        if ($parameters['distributor']) {
            $query->condition('D.distributor_id', $parameters['distributor'], '=');
        }
    }elseif(!empty($parameters['salesman'])) {
        if($parameters['salesman']){
            $query->join('salesman_distributor_map', 'sd','sd.distributor_id = D.distributor_id');
            $query->condition('sd.salesman_id', $parameters['salesman'], '=');
        }
    }elseif(!empty($parameters['juris'])) {
        if($parameters['juris']){
            $query->join('salesman_distributor_map', 'SD', 'SD.distributor_id = D.distributor_id');
            $query->join('employee', 'E', 'E.employee_id = SD.salesman_id');
            $query->condition('E.juris_id', $parameters['juris'], '=');
        }
    }
    if (!empty($parameters['year'])) {//查询条件
        if ($parameters['year']) {
            $query->condition('M.year', $parameters['year'], '=');
        }
    }
    if (!empty($parameters['month'])) {//查询条件
        if ($parameters['month']) {
            $query->condition('M.month', $parameters['month'], '=');
        }
    }

    $query->orderBy('M.monthly_report_id', 'DESC');
    if (!empty($parameters['cursor']) && !empty($parameters['comparator'])) { //游标翻页
        $query->condition('M.monthly_report_id', $parameters['cursor'], $parameters['comparator']);
    }
    $query->range(0,10);
    
    $results = $query->execute();
    $monthly_report_list = [];
    if(!empty($results)){
        foreach ($results as $result) {
            $monthly_report_list[] = $result;
        }
    }
    $object_monthly_report_list = (object)["data"=>$monthly_report_list];
    return  $object_monthly_report_list;
}

function mobile_service_monthly_report_add($parameters){
    global $user;
    $module_name="monthly_report";
    $id = !empty($parameters['monthly_report_id'])?$parameters['monthly_report_id']:'';
    if (empty($id)) { //add new brand_sales
        if(!user_access('add '.$module_name)){
            return ['option'=>0,'errorNum'=>3];
        }
        $nid = db_insert('monthly_report') // Table name no longer needs {}
        ->fields(array(
            'year' => $parameters['year'],
            'month' => $parameters['month'],
            'distributor_id' => $parameters['distributor_id'],
            'this_month_received_payment' => $parameters['this_month_received_payment'],
            'accounts_receivable' => $parameters['accounts_receivable'],
            'payment_overdue' => $parameters['payment_overdue'],
            'payment_credit' => $parameters['payment_credit'],
            'paulin_number' => $parameters['paulin_number'],
            'paulin_overdue' => $parameters['paulin_overdue'],
            'damage_info' => $parameters['damage_info'],
            'payment_info' => $parameters['payment_info'],
            'promotion_info' => $parameters['promotion_info'],
            'unqualified_info' => $parameters['unqualified_info'],
            'accident_info' => $parameters['accident_info'],
            'pending_issues' => $parameters['pending_issues'],
            'competitor_info' => $parameters['competitor_info'],
            'next_month_task' => $parameters['next_month_task'],
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->execute();
        $result_option = (object)["option" => 1];
        return $result_option;
    } else {
        if(!mobile_user_edit_access($module_name,$module_name.'_id',$id,'edit own '.$module_name,'edit all '.$module_name)){
            return ['option'=>0,'errorNum'=>3];
        }
        $nid = db_update('monthly_report') // edit exsting store. todo: update only modified fields
        ->fields(array(
            'year' => $parameters['year'],
            'month' => $parameters['month'],
            'distributor_id' => $parameters['distributor_id'],
            'this_month_received_payment' => $parameters['this_month_received_payment'],
            'accounts_receivable' => $parameters['accounts_receivable'],
            'payment_overdue' => $parameters['payment_overdue'],
            'payment_credit' => $parameters['payment_credit'],
            'paulin_number' => $parameters['paulin_number'],
            'paulin_overdue' => $parameters['paulin_overdue'],
            'damage_info' => $parameters['damage_info'],
            'payment_info' => $parameters['payment_info'],
            'promotion_info' => $parameters['promotion_info'],
            'unqualified_info' => $parameters['unqualified_info'],
            'accident_info' => $parameters['accident_info'],
            'pending_issues' => $parameters['pending_issues'],
            'competitor_info' => $parameters['competitor_info'],
            'next_month_task' => $parameters['next_month_task'],
            'timestamp' => time(),))
            -> condition('monthly_report_id',$id, '=')
            ->execute();
        if($nid > 0){
            $result_option = (object)["option" => 1];
            return $result_option;
        }
        $result_option = (object)["option" => 0];
        return $result_option;
    }
}

function mobile_service_sales_log_list($parameters){
    global $user;
    $user_info = _get_user_info1();
    $query = db_select('employee', 'E');
    $query->join('sales_log', 'L', 'L.salesman_id=E.employee_id');
    $query->fields('L', array('sales_log_id', 'sales_log_date', 'client', 'phone','work_title','log_ip', 'log_addr','addr_id','salesman_id'));
    $query->addField('E', 'employee_name');
    if(!user_access('view all sales_log') && user_access('view own sales_log')){
        $query->condition('L.author_uid',$user->uid, '=');
    }
    if (!empty($parameters['salesman'])) {//查询条件
        if ($parameters['salesman']) {
            $query->condition('e.employee_id', $parameters['salesman'], '=');
        }
    }
    $datestr = '';
    if (!empty($parameters['year'])) {//查询条件
        if ($parameters['year']) {
            $datestr .= $parameters['year'] . '-';
        }
    }
    if (!empty($parameters['month'])) {//查询条件
        if ($month = $parameters['month']) {
            if ($month < 10)
                $datestr .= '0' . $parameters['month'];
            else
                $datestr .= $parameters['month'];
        }
    }
    if ($datestr) {
        $query->condition('L.sales_log_date', db_like($datestr) . '%', 'LIKE');
    }
    if (!empty($parameters['employee_list']) && $parameters['employee_list'] != "default") {//查询条件
        if ($parameters['employee_list']) {
            $query->condition('L.author_uid', $parameters['employee_list']);
        }
    }
    if($parameters['employee_list'] == "default" || $parameters['employee_list'] == ""){
        if($user_info['role'] != 'administrator') {
            $salesmans_ids = get_salesman_by_self1($user);
            $query->condition('L.author_uid', $salesmans_ids, 'in');
        }
    }
    if(!empty($parameters['status'])){
        if($parameters['status'] == '2'){
            $query->where('L.log_ip is Not Null');
        }else if($parameters['status'] == '1'){
            $query->where('L.log_ip is Null');
        }
    }
    $query->leftJoin('addr', 'A', 'A.addr_id=L.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');

    $query->orderBy('L.sales_log_id', 'DESC');
    if (!empty($parameters['cursor']) && !empty($parameters['comparator'])) { //游标翻页
        $query->condition('L.sales_log_id', $parameters['cursor'], $parameters['comparator']);
    }
    $query->range(0,10);
    
    $results = $query->execute();
    $sales_log_list = [];
    if(!empty($results)){
        foreach ($results as $result) {
            $sales_log_list[] = $result;
        }
    }
    $object_sales_log_list = (object)["data"=>$sales_log_list];
    return  $object_sales_log_list;
}

function mobile_service_sales_log_add($parameters){
    global $user;
    $module_name="sales_log";
    $id = !empty($parameters['sales_log_id'])?$parameters['sales_log_id']:'';
    $log_addr = getIPLoc_QQ($_SERVER["REMOTE_ADDR"]) ;

    if (empty($id)) { //add new sales_log
        if(!user_access('add '.$module_name)){
            return ['option'=>0,'errorNum'=>3];
        }
        $nid = db_insert('sales_log') // Table name no longer needs {}
        ->fields(array(
            'sales_log_date' =>$parameters['sales_log_date'],
            'salesman_id' => $parameters['salesman_id'],
            'addr_id' => $parameters['addr_id'],
            'addr_details' => $parameters['addr_details'],
            'client' => $parameters['client'],
            'contact' => $parameters['contact'],
            'phone' => $parameters['phone'],
            'work_title' => $parameters['work_title'],
            'work_details' => $parameters['work_details'],
            'log_ip' => $_SERVER["REMOTE_ADDR"],
            'log_addr' => $log_addr,
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->execute();
        $result_option = (object)["option" => 1];
        return $result_option;
    } else {
        if(!mobile_user_edit_access($module_name,$module_name.'_id',$id,'edit own '.$module_name,'edit all '.$module_name)){
            return ['option'=>0,'errorNum'=>3];
        }
        $nid = db_update('sales_log')
        ->fields(array(
            'sales_log_date' =>$parameters['sales_log_date'],
            'salesman_id' => $parameters['salesman_id'],
            'addr_id' => $parameters['addr_id'],
            'addr_details' => $parameters['addr_details'],
            'client' => $parameters['client'],
            'contact' => $parameters['contact'],
            'phone' => $parameters['phone'],
            'work_title' => $parameters['work_title'],
            'work_details' => $parameters['work_details'],
            'log_ip' => $_SERVER["REMOTE_ADDR"],
            'log_addr' => $log_addr,
            'timestamp' => time(),))
            -> condition('sales_log_id',$id, '=')
            ->execute();
        if($nid > 0){
            $result_option = (object)["option" => 1];
            return $result_option;
        }
        $result_option = (object)["option" => 0];
        return $result_option;
    }
}


function  mobile_service_invoice_stats_list($parameters){
    $start  = $parameters['page_count'] * 10;
    $geo_level = $parameters['geo_level'];
    if ($geo_level == '0') {
        $join_column = 'country_id';
    }else if ($geo_level == '1') {
        $join_column = 'province_id';
    } else if ($geo_level == '2') {
        $join_column = 'city_id';
    } else if ($geo_level == '3') {
        $join_column = 'county_id';
    } else if ($geo_level == '4') {
        $join_column = 'town_id';
    } else {
        $join_column = 'village_id';
    }

//    $map_or_zone = $parameters['map_or_zone'];
    $map_or_zone = 'map';
    $juris = $parameters['juris'];
    $salesman = $parameters['salesman'];
    $distributor = $parameters['distributor'];
    $national_id = $parameters['national_id'];

    $query = db_select('invoice', 'I');
    $query->leftjoin('users', 'U', 'U.uid=I.author_uid');
    $query->join('employee', 'E', 'E.employee_id=I.salesman_id');
    $query->join('distributor', 'D', 'D.distributor_id=I.distributor_id');
    $query->join('sales_type', 'ST', 'ST.sales_type_id=I.sales_type_id');
    $query->join('product_sku', 'SV', 'SV.product_sku_id=I.sacfvariety_id');

    $query->addField('D', 'distributor_name');
    if ($map_or_zone == 'map') {
        $query->join('addr', 'A1', 'A1.addr_id=D.addr_id');
        if ($geo_level <= 2) {
            $query->join('addr', 'A2', "A2.addr_id=A1.$join_column");
        } else {
            $query->join('addr', 'A2', "A2.addr_id=A1.$join_column");
            $query->join('addr', 'A3', "A3.addr_id=A2.pid");
        }
    } else {
        if (!empty($distributor)) {
            // join nothing
        } else if (!empty($salesman)) {
            //join nothing
        } else if (!empty($juris)) {
            $query->join('salesman_distributor_map', 'SD', 'SD.distributor_id = D.distributor_id');
            $query->join('employee', 'EE', 'EE.employee_id = SD.salesman_id');
        }
    }

    $query->leftJoin('addr', 'A', 'A.addr_id=I.delivery_addr_id');
    $query->leftJoin('addr', 'A7', 'A.province_id=A7.addr_id');
    $query->leftJoin('addr', 'A8', 'A.city_id=A8.addr_id');
    $query->leftJoin('addr', 'A9', 'A.county_id=A9.addr_id');

    if ($map_or_zone == 'map') {
        if ($geo_level <= 2) {
            $query->condition('A2.national_id', $national_id);
        } else {
            $query->condition('A3.national_id', $national_id);
            $query->condition('A2.name', $parameters['geo_name']);
        }
    } else {
        if (!empty($distributor)) {
            $query->condition('D.distributor_id', $distributor);
        } else if (!empty($salesman)) {

            $query->condition('I.salesman_id', $salesman);
        } else if (!empty($juris)) {
            $query->condition('EE.juris_id', $juris);
        }
    }
    $datestr = '';
    if (!empty($parameters['year'])) {//查询条件
        if ($parameters['year']) {
            $datestr .= $parameters['year'] . '-';
        }
    }
    if (!empty($parameters['month'])) {//查询条件
        if ($month = $parameters['month']) {
            if ($month < 10)
                $datestr .= '0' . $parameters['month'];
            else
                $datestr .= $parameters['month'];
        }
    }
    if ($datestr) {
        $query->condition('I.invoice_date', db_like($datestr) . '%', 'LIKE');
    }
    $query->addField('A7', 'name', 'province');
    $query->addField('A8', 'name', 'city');
    $query->addField('A9', 'name', 'county');
    $query->fields('I');
    $query->addField('E', 'employee_name', 'salesman');
    $query->addField('ST', 'sales_type_name');
    $query->addField('SV', 'variety_name');
    $query->addField('SV', 'proportion');
    $query->addField('SV', 'SM');
    $query->orderBy('I.timestamp', 'DESC');
    $query->range($start,10);
    $results = $query->execute();
    $invoice_stats_list = [];
    if(!empty($results)){
        foreach ($results as $result) {
            $invoice_stats_list[] = $result;
        }
    }
    $object_invoice_stats_list = (object)["data"=>$invoice_stats_list];
    return  $object_invoice_stats_list;
}

function mobile_service_monthly_report_stats_list($parameters){
    $start  = $parameters['page_count'] * 10;
    $geo_level = $parameters['geo_level'];
    if ($geo_level == '0') {
        $join_column = 'country_id';
    }else if ($geo_level == '1') {
        $join_column = 'province_id';
    } else if ($geo_level == '2') {
        $join_column = 'city_id';
    } else if ($geo_level == '3') {
        $join_column = 'county_id';
    } else if ($geo_level == '4') {
        $join_column = 'town_id';
    } else {
        $join_column = 'village_id';
    }

    $map_or_zone = 'map';
    $juris = $parameters['juris'];
    $salesman = $parameters['salesman'];
    $distributor = $parameters['distributor'];

    $sub_query_year_month = db_select('years', 'Y');
    $sub_query_year_month->join('months', 'M');
    $sub_query_year_month->condition('Y.year', $parameters['year']);
    $sub_query_year_month->condition('M.month', $parameters['month']);
    $sub_query_year_month->addField('Y', 'year');
    $sub_query_year_month->addField('M', 'month');

    $query = db_select('distributor', 'D');
    if ($map_or_zone == 'map') {
        $query->join('addr', 'A1', 'A1.addr_id=D.addr_id');
        if ($geo_level <= 2) {
            $query->join('addr', 'A2', "A2.addr_id=A1.$join_column");
        } else {
            $query->join('addr', 'A2', "A2.addr_id=A1.$join_column");
            $query->join('addr', 'A3', "A3.addr_id=A2.pid");
        }
    }else {
        if (!empty($distributor)) {
            // join nothing
        } else if (!empty($salesman)) {
            $query->join('salesman_distributor_map', 'SD', 'SD.distributor_id = D.distributor_id');
        } else if (!empty($juris)) {
            $query->join('salesman_distributor_map', 'SD', 'SD.distributor_id = D.distributor_id');
            $query->join('employee', 'E', 'E.employee_id = SD.salesman_id');
        }
    }
    $query->join($sub_query_year_month, 'T');
    $query->leftJoin('monthly_report', 'MR', 'MR.year=T.year and MR.month=T.month and MR.distributor_id=D.distributor_id');
    $query->leftJoin('employee','EM','MR.author_uid = EM.employee_id');
    $query->addField('EM', 'employee_name');
//    $query->fields('MR');
    if ($map_or_zone == 'map') {
        if ($geo_level <= 2) {
            $query->condition('A2.national_id', $parameters['national_id']);
        } else {
            $query->condition('A3.national_id', $parameters['national_id']);
            $query->condition('A2.name', $parameters['geo_name']);
        }
    } else {
        if (!empty($distributor)) {
            $query->condition('D.distributor_id', $distributor);
        } else if (!empty($salesman)) {
            $query->condition('SD.salesman_id', $salesman);
        } else if (!empty($juris)) {
            $query->condition('E.juris_id', $juris);
        }
    }

    $query->addField('D', 'distributor_id');
    $query->addField('D', 'distributor_name');
    $query->addField('D', 'inorout');
    $query->addField('T', 'year');
    $query->addField('T', 'month');
    $query->addField('MR', 'this_month_received_payment');
    $query->addField('MR', 'accounts_receivable');
    $query->addField('MR', 'payment_overdue');
    $query->addField('MR', 'payment_credit');
    $query->orderBy('MR.timestamp', 'DESC');
    $query->range($start,10);
    $results = $query->execute();
    $monthly_report_stats_list = [];
    if(!empty($results)){
        foreach ($results as $result) {
            $monthly_report_stats_list[] = $result;
        }
    }
    $object_monthly_report_stats_list = (object)["data"=>$monthly_report_stats_list];
    return  $object_monthly_report_stats_list;
}

function getIPLoc_QQ($queryIP){
    $url = 'http://ip.qq.com/cgi-bin/searchip?searchip1='.$queryIP;
    $ch = curl_init($url);
    curl_setopt($ch,CURLOPT_ENCODING ,'gb2312');
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
    $result = curl_exec($ch);
    $result = mb_convert_encoding($result, "utf-8", "gb2312"); // 编码转换，否则乱码
    curl_close($ch);
    preg_match("@<span>(.*)</span></p>@iU",$result,$ipArray);
    $loc = $ipArray[1];
    if($loc == '目前暂时没有您的IP信息,&nbsp;&nbsp;期待您的分享'){
        $loc = '用户IP地址更新中...';
    }
    return $loc;
}


function _get_user_info1($uid = null) {
    global $user;
    if (empty($uid)) {
        $user_system = $user;
    }
    else {
        $user_system = user_load($uid);
    }
    $user_info = array();
    $employee_roles = array('administrator',  '销售员', '销售管理员', '农化管理员', '农化服务员','公司领导');
    $distributor_roles = array('经销商');
    $farmer_roles = array('农户');
    $flag = '';
    if (!empty($user_system)) {
        foreach ($user_system->roles as $role) {
            if (in_array($role, $employee_roles)) {
                $user_info['role'] = $role;
                $flag = 'employee';
            }
            if (in_array($role, $distributor_roles)) {
                $user_info['role'] = $role;
                $flag = 'distributor';
            }
            if (in_array($role, $farmer_roles)) {
                $user_info['role'] = $role;
                $flag = 'farmer';
            }
        }
        if ($flag == "employee") {
            $result = db_select('employee', 'E')
                ->fields('E')
                ->condition('E.' . 'employee_id', $user_system->uid, '=')
                ->execute()
                ->fetchObject();

            if (!empty($result)) {
                $user_info['name'] = $result->employee_name;
                $user_info['cell'] = $result->cell;
                $user_info['address'] = $result->address;
                $user_info['department'] = $result->department_id;
                $user_info['juris'] = $result->juris_id;
                $user_info['manager'] = $result->manager_uid;
                $user_info['position'] = $result->position;
            }
        }
        elseif ($flag == "distributor") {
            $result = db_select('distributor', 'D')
                ->fields('D')
                ->condition('D.' . 'distributor_id', $user_system->uid, '=')
                ->execute()
                ->fetchObject();

            if (!empty($result)) {
                $user_info['name'] = $result->distributor_name;
                $user_info['cell'] = $result->cell;
                $user_info['address'] = $result->addr_details;
                $user_info['inorout'] = $result->inorout;
            }
        }
        elseif ($flag == "farmer") {
            $result = db_select('farmer', 'F')
                ->fields('F')
                ->condition('F.' . 'farmer_id', $user_system->uid, '=')
                ->execute()
                ->fetchObject();

            if (!empty($result)) {
                $user_info['name'] = $result->farmer_name;
                $user_info['cell'] = $result->cell;
                $user_info['address'] = $result->addr_details;
                $user_info['type'] = $result->type;
            }
        }
    }
    return $user_info;
}


function get_salesman_by_self1($user){
    $query = db_select('employee', 'e1');
    $query->leftJoin('employee', 'e2', 'e2.manager_uid = e1.employee_id');
    $query->leftJoin('employee', 'e3', 'e3.manager_uid = e2.employee_id');
    $query->leftJoin('employee', 'e4', 'e4.manager_uid = e3.employee_id');
    $query->leftJoin('employee', 'e5', 'e5.manager_uid = e4.employee_id');
    $query->leftJoin('employee', 'e6', 'e6.manager_uid = e5.employee_id');
    $query->condition('e1.employee_id', $user->uid, '=');
    $query->addField('e1', 'employee_id ','employee_id');
    $query->addField('e2', 'employee_id ','one_employee_id');
    $query->addField('e3', 'employee_id','two_employee_id');
    $query->addField('e4', 'employee_id','three_employee_id');
    $query->addField('e5', 'employee_id','four_employee_id');
    $query->addField('e6', 'employee_id','five_employee_id');
    $results = $query->execute()->fetchAll();
    foreach($results as $rows){
        $rows->employee_id?$result[$rows->employee_id] = $rows->employee_id:"";
        $rows->one_employee_id?$result[$rows->one_employee_id] = $rows->one_employee_id:"";
        $rows->two_employee_id?$result[$rows->two_employee_id] = $rows->two_employee_id:"";
        $rows->three_employee_id?$result[$rows->three_employee_id] = $rows->three_employee_id:"";
        $rows->four_employee_id? $result[$rows->four_employee_id] = $rows->four_employee_id:"";
        $rows->five_employee_id? $result[$rows->five_employee_id] = $rows->five_employee_id:"";
    }
    return $result;
}



